package com.example.sxmall.service.action;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.sxmall.auth.Authentication;
import com.example.sxmall.auth.UserInfo;
import com.example.sxmall.controller.shopCart.ProductEnums;
import com.example.sxmall.controller.shopCart.vo.ProductVO;
import com.example.sxmall.controller.shopCart.vo.ShopCartVO;
import com.example.sxmall.controller.shopCart.vo.StoreProductVO;
import com.example.sxmall.controller.shopCart.vo.StoreVO;
import com.example.sxmall.redis.RedisService;
import com.example.sxmall.redis.ShopCartKey;
import com.example.sxmall.service.ShopCartService;
import com.example.sxmall.service.dto.OperateCartDTO;
import com.example.sxmall.service.dto.ShopCartDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author whh-yt
 * @Date 2022/3/17 4:56 下午
 */
@Service
public class ActionCartService implements ICartAction {

    /**
     * 订单操作动作
     */
    private final static Map<Integer, ICartAction> ACTION_CART_MAP = new HashMap<>(8);

    @Autowired
    protected RedisService redisService;
    @Autowired
    protected CommonProductService commonProductService;
    @Autowired
    protected ProductService productService;

    public Map<Integer, ICartAction> getActionCartMap() {
        return ACTION_CART_MAP;
    }

    /**
     * 查询购物车信息
     */
    @Override
    public ShopCartVO execute(OperateCartDTO operateCartDTO) {
        UserInfo userInfo = Authentication.getUserInfo();
        // 获取出当前购物车里面的信息
        ShopCartDTO shopCartCache = redisService.get(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId(), ShopCartDTO.class);
        ShopCartVO shopCartVO = new ShopCartVO();
        if (Objects.isNull(shopCartCache)) {
            shopCartVO.setVersion(ShopCartService.SHOPCART_VERSION);
            shopCartVO.setStoreProductList(new ArrayList<>());
            shopCartVO.setInvalidProductList(new ArrayList<>());
            shopCartVO.setPaymentAmount("");
            return shopCartVO;
        }
        // 购物车 店铺+商品
        List<StoreProductVO> storeProductListCache = shopCartCache.getStoreProductList();
        // 取出全部商品sku当前商品的状态
        List<String> shopCartSkuList = storeProductListCache.stream().flatMap(item -> item.getProductList().stream()).map(ProductVO::getSkuCode).distinct().collect(Collectors.toList());
        List<MaterialEntity> materialEntityList = commonProductService.listMaterialBySkuList(shopCartSkuList);
        Map<String, MaterialEntity> skuInfoMap = materialEntityList.stream().collect(Collectors.toMap(MaterialEntity::getSkuCode, item -> item));
        // 对购物车里面的商品进行校验是否上下架
        storeProductListCache.stream().flatMap(item -> item.getProductList().stream())
                .forEach(productVO -> productVO.setOnShelf(skuInfoMap.get(productVO.getSkuCode()).getOnShelf()));
        shopCartCache.setStoreProductList(storeProductListCache);
        redisService.set(ShopCartKey.SHOP_CART_KEY, userInfo.getUnionId(), shopCartCache);
        // 购物车 上架商品列表 下架商品列表
        List<StoreProductVO> storeProductList = new ArrayList<>();
        List<StoreProductVO> invalidProductList = new ArrayList<>();
        for (StoreProductVO storeProductVO : storeProductListCache) {
            StoreVO store = storeProductVO.getStore();
            List<ProductVO> productListCache = storeProductVO.getProductList();
            StoreProductVO validProduct = new StoreProductVO();
            validProduct.setStore(store);
            validProduct.setProductList(new ArrayList<>());
            StoreProductVO invalidProduct = new StoreProductVO();
            invalidProduct.setStore(store);
            invalidProduct.setProductList(new ArrayList<>());
            // 将商品按照上下架分组
            productListCache.stream().filter(item -> ProductEnums.ProductOnShelfEnum.OFF_SHELF.getType().equals(item.getOnShelf()) ?
                    invalidProduct.getProductList().add(item) : validProduct.getProductList().add(item)).count();
            storeProductList.add(validProduct);
            invalidProductList.add(invalidProduct);
        }
        storeProductList.removeIf(item -> CollectionUtils.isEmpty(item.getProductList()));
        invalidProductList.removeIf(item -> CollectionUtils.isEmpty(item.getProductList()));
        shopCartVO.setVersion(shopCartCache.getVersion());
        shopCartVO.setStoreProductList(storeProductList);
        shopCartVO.setInvalidProductList(invalidProductList);
        if (CollectionUtils.isNotEmpty(storeProductList)) {
            BigDecimal paymentAmount = storeProductList.stream()
                    .map(store -> store.getProductList().stream()
                            .filter(ProductVO::getCheck)
                            .map(o -> o.getUnitPrice().multiply(BigDecimal.valueOf(o.getBuyCount())))
                            .reduce(BigDecimal.ZERO, BigDecimal::add))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            shopCartVO.setPaymentAmount(paymentAmount.setScale(2, RoundingMode.DOWN).toPlainString());
        } else {
            shopCartVO.setPaymentAmount(BigDecimal.ZERO.setScale(2, RoundingMode.DOWN).toPlainString());
        }

        shopCartVO.setCheckAll(storeProductList.stream().flatMap(storeProductVO -> storeProductVO.getProductList().stream()).allMatch(ProductVO::getCheck));
        //计算营销等
        return shopCartVO;
    }
}
